package com.feng.gulimall.member.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.utils.PageUtils;
import com.feng.common.utils.Query;
import com.feng.common.vo.GiteeUser;
import com.feng.common.vo.SocialUser;
import com.feng.gulimall.member.dao.MemberDao;
import com.feng.gulimall.member.entity.MemberEntity;
import com.feng.gulimall.member.entity.MemberLevelEntity;
import com.feng.gulimall.member.exception.PhoneException;
import com.feng.gulimall.member.exception.UsernameException;
import com.feng.gulimall.member.service.MemberLevelService;
import com.feng.gulimall.member.service.MemberService;
import com.feng.gulimall.member.vo.MemberLoginVo;
import com.feng.gulimall.member.vo.MemberRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.Map;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {
    @Autowired
    private MemberLevelService memberLevelService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void register(MemberRegisterVo vo) {
        MemberEntity memberEntity = new MemberEntity();
        MemberLevelEntity memberLevelEntity= memberLevelService.getDefaultLevel();
        memberEntity.setLevelId(memberLevelEntity.getId());
        //检查用户名和手机号是否唯一
        checkPhoneUnique(vo.getPhone());
        checkUserNameUnique(vo.getUserName());
        memberEntity.setMobile(vo.getPhone());
        memberEntity.setUsername(vo.getUserName());
        memberEntity.setNickname(vo.getUserName());
        //密码要进行加密存储
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        String encode = passwordEncoder.encode(vo.getPassword());
        memberEntity.setPassword(encode);
        //其他的默认信息
        this.save(memberEntity);
    }

    @Override
    public MemberEntity login(MemberLoginVo memberLoginVo) {
        String loginacct = memberLoginVo.getLoginacct();
        String password = memberLoginVo.getPassword();
        //去数据库查询
        LambdaQueryWrapper<MemberEntity> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberEntity::getEmail,loginacct).or().eq(MemberEntity::getMobile,loginacct);
        MemberEntity one = this.getOne(queryWrapper);
        if(one==null){
            //登录失败
            return null;
        }
        else{
            String password1 = one.getPassword();
            BCryptPasswordEncoder bCryptPasswordEncoder=new BCryptPasswordEncoder();
            boolean matches = bCryptPasswordEncoder.matches(password, password1);
            if(matches==true){
                //登录成功
                return one;
            }
            else{
                //密码错误
                return null;
            }
        }
    }
    @Transactional
    @Override
    public MemberEntity login(GiteeUser giteeUser) {
        //社交账号登录，具有登录注册逻辑
        //首先判断用户是否注册
        long id = giteeUser.getId();
        LambdaQueryWrapper<MemberEntity> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberEntity::getSocialUid,id+"");
        MemberEntity one = this.getOne(queryWrapper);
        if(!ObjectUtils.isEmpty(one)){
            return one;
        }
        else{
            //2、没有查到当前社交用户对应的记录我们就需要注册一个
            MemberEntity memberEntity=new MemberEntity();
            memberEntity.setNickname(giteeUser.getName());
            memberEntity.setEmail(giteeUser.getEmail());
            memberEntity.setSocialUid(giteeUser.getId()+"");
            memberEntity.setHeader(giteeUser.getAvatar_url());
            memberEntity.setCreateTime(new Date());
            this.save(memberEntity);
            return memberEntity;

        }

    }



    private void checkUserNameUnique(String userName) throws UsernameException{
        Integer usernameCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));

        if (usernameCount > 0) {
            throw new UsernameException();
        }
    }

    private void checkPhoneUnique(String phone) throws PhoneException{
        Integer phoneCount = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));

        if (phoneCount > 0) {
            throw new PhoneException();
        }
    }

}
